package com.da.web.sys_user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.da.web.sys_user.entity.PageParm;
import com.da.web.sys_user.entity.SysUser;
import com.da.web.sys_user.mapper.SysUserMapper;
import com.da.web.sys_user.service.SysUserService;
import com.da.web.sys_user_role.entity.SysUserRole;
import com.da.web.sys_user_role.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author da
 * @time 2023/12/1 上午 10:19
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public IPage<SysUser> list(PageParm parm) {
        //构造分页对象
        IPage<SysUser> page = new Page<>();
        page.setCurrent(parm.getCurrentPage());
        page.setSize(parm.getPageSize());
        //构造查询条件,模糊查询
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(parm.getNickName())) {
            query.lambda().like(SysUser::getNickName, parm.getNickName());
        }
        if (StrUtil.isNotEmpty(parm.getPhone())) {
            query.lambda().like(SysUser::getPhone, parm.getPhone());
        }
        //分页查询
        return this.baseMapper.selectPage(page, query);
    }

    //开启事务
    @Transactional
    @Override
    public void add(SysUser user) {
        //新增用户
        int insert = this.baseMapper.insert(user);
        //保存用户角色
        if (insert > 0) {
            SysUserRole role = new SysUserRole();
            role.setRoleId(user.getRoleId());
            role.setUserId(user.getUserId());
            sysUserRoleService.save(role);
        }
    }

    @Transactional
    @Override
    public void edit(SysUser user) {
        int i = this.baseMapper.updateById(user);
        if (i > 0) {
            //先删除原来的角色
            QueryWrapper<SysUserRole> query = new QueryWrapper<>();
            query.lambda().eq(SysUserRole::getUserId,user.getUserId());
            sysUserRoleService.remove(query);
            //重新保存用户角色
            SysUserRole role = new SysUserRole();
            role.setRoleId(user.getRoleId());
            role.setUserId(user.getUserId());
            sysUserRoleService.save(role);
        }
    }
}
